package com.neuedu.my12306.web;

import java.util.Hashtable;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;



public class SessionListener implements ServletContextListener, HttpSessionAttributeListener {
	ServletContext context = null;
	private Map<String, String> onlineUserMap ;
	
	@Override
	public void attributeAdded(HttpSessionBindingEvent event) {
		// 当调用session.setAttribute()方法时，这个方法会自动执行；即tomcat服务器都会自动调用方法
		// 注意：每次调用session.setAttribute()方法时，都会触发该事件；
		HttpSession session = event.getSession();
		String userName = (String) session.getAttribute("LOGIN_USER");
		if (userName != null) {
			
			onlineUserMap.put(userName, userName);
			System.out.println(userName+"上线了！,当前在线用户数： "+onlineUserMap.size());

		}
		
	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent event) {
		HttpSession session = event.getSession();// 
		//HttpSession session =  (HttpSession)event.getSource();
		System.out.println("session id: :::  "+session.getId());
		
		String attributeName = event.getName();
		if ("LOGIN_USER".contentEquals(attributeName)) {
			String userName = (String) event.getValue();
			if (userName != null) {
				onlineUserMap.remove(userName);
				System.out.println(userName + " 下线了,当前在线用户数："+onlineUserMap.size());
			}
		}
	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent event) {
		//HttpSession session = event.getSession();
		String attributeName = event.getName();
		if ("LOGIN_USER".contentEquals(attributeName)) {
			String userName = (String) event.getValue();
			if (userName!=null) {
				onlineUserMap.put(userName, userName);
				System.out.println(userName+"上线了！,当前在线用户数： "+onlineUserMap.size());
			}
			

		}
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		
		context = sce.getServletContext();
		
	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		//当服务器启动时，监听器启动后，创建ServletContext对象
		context = sce.getServletContext();
		onlineUserMap = new Hashtable<String, String>();
		context.setAttribute("ONLINES", onlineUserMap);
		
		
	}

}
